package cn.snowheart

import groovy.json.JsonOutput
import groovy.json.JsonSlurper

/**
 * JSON 生成和解析
 *
 * @author liuwanxiang
 * @version 2019/05/31
 */
class JsonExample {

    static void main(String[] args) {

        // 文本解析
        def slurper = new JsonSlurper()
        def obj = slurper.parseText('{"name" : "zhangsan", "age" : 25}')
        println obj.name
        println obj.age

        // 解析整数列表
        def list = slurper.parseText('{"list": [1,2,3,4]}')
        list.each { println it }

        // 对象 --> JSON
        println JsonOutput.toJson(obj)

        // 对象 --> JSON
        def student = new Student()
        student.name = "stu"
        student.setAge(20)
        println JsonOutput.toJson(student)
    }

    static class Student{
        String name
        int age
    }
}
